<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { UserOutlined } from '@ant-design/icons-vue'
import request, { getServerUrl } from '@/utils/request'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userIsLoggedIn = ref(false)
const userName = ref('')
const userAvatar = ref('')
const userStore = useUserStore()

// 检查用户是否已登录
const checkLoginStatus = () => {
  // 直接从store的state获取user，不使用getUser方法
  const user = userStore.user
  
  if (user && user.username) {
    userName.value = user.username
    userIsLoggedIn.value = true
    
    // 设置用户头像
    if (user.avatarUrl) {
      // 检查是否为完整URL
      if (user.avatarUrl.startsWith('http') || user.avatarUrl.startsWith('data:')) {
        userAvatar.value = user.avatarUrl
      } else {
        // 如果是相对路径，添加服务器地址
        userAvatar.value = getServerUrl() + user.avatarUrl
      }
    } else {
      userAvatar.value = ''
    }
  } else {
    userIsLoggedIn.value = false
    userAvatar.value = ''
  }
}

// 组件挂载时检查一次
onMounted(() => {
  checkLoginStatus()
  
  // 添加存储事件监听，当其他页面修改localStorage时响应
  window.addEventListener('storage', checkLoginStatus)
  
  // 创建一个自定义事件处理登录状态变化
  window.addEventListener('login-state-changed', checkLoginStatus)
})

const logout = () => {
  userIsLoggedIn.value = false
  userAvatar.value = ''
  userStore.logout()
  router.push('/')
  // 触发登录状态变化事件
  window.dispatchEvent(new Event('login-state-changed'))
}

const goToLogin = () => {
  router.push('/login')
}

const goToRegister = () => {
  router.push('/register')
}

const goToUserProfile = () => {
  // 跳转到个人中心页面
  router.push('/profile')
}

const goToIdentify = () => {
  router.push('/identify')
}
</script>

<template>
  <a-layout-header class="header">
    <div class="logo">垃圾识别系统</div>
    
    <!-- 主菜单：无论是否登录都显示首页 -->
    <a-menu
      theme="dark"
      mode="horizontal"
      :selected-keys="[$route.name]"
      class="main-menu"
    >
      <a-menu-item key="home">
        <router-link to="/">首页</router-link>
      </a-menu-item>
      <a-menu-item key="records" v-if="userIsLoggedIn">
        <router-link to="/records">识别记录</router-link>
      </a-menu-item>
    </a-menu>
    
    <!-- 用户操作区：根据登录状态显示不同内容 -->
    <div class="user-actions">
      <template v-if="userIsLoggedIn">
        <!-- 用户头像下拉菜单 -->
        <a-dropdown :trigger="['click']" placement="bottomRight">
          <div class="user-avatar-wrapper">
            <a-avatar :src="userAvatar" class="user-avatar" v-if="userAvatar">
              <!-- 头像图片会自动显示 -->
            </a-avatar>
            <a-avatar class="user-avatar" v-else>
              {{ userName.charAt(0).toUpperCase() }}
            </a-avatar>
            <span class="username">{{ userName }}</span>
          </div>
          <template #overlay>
            <a-menu>
              <a-menu-item key="profile" @click="goToUserProfile">
                <user-outlined />
                个人中心
              </a-menu-item>
              <a-menu-divider />
              <a-menu-item key="logout" @click="logout">
                退出登录
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </template>
      <template v-else>
        <a-button type="link" @click="goToLogin">登录</a-button>
        <a-button type="primary" @click="goToRegister">注册</a-button>
      </template>
    </div>
  </a-layout-header>
</template>

<style scoped>
.logo {
  float: left;
  color: white;
  font-size: 18px;
  margin-right: 30px;
}
.header {
  display: flex;
  align-items: center;
}
.main-menu {
  flex: 1;
}
.user-actions {
  display: flex;
  align-items: center;
}
.user-actions .ant-btn {
  color: white;
}
.user-actions .ant-btn-primary {
  background-color: #1677ff;
}
.user-avatar-wrapper {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 0 8px;
}
.user-avatar {
  background-color: #1677ff;
  color: white;
  width: 38px;
  height: 38px;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  font-size: 16px;
  border: 2px solid rgba(255, 255, 255, 0.2);
}
.user-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.username {
  color: white;
  margin-left: 10px;
  font-weight: 500;
}
</style> 